package com.example.b_app;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_username;
    private EditText edit_password;
    private CheckBox checkBox2;
    private Button button_logi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        edit_username = (EditText) findViewById(R.id.edit_username);
        edit_password = (EditText) findViewById(R.id.edit_password);
        checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
        button_logi = (Button) findViewById(R.id.button_logi);

        button_logi.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_logi:
                submit();

                break;
        }
    }

    private void submit() {
        // validate
        String username = edit_username.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "username不能为空", Toast.LENGTH_SHORT).show();
            return;
        }


        String password = edit_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "password不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!(username.equals("admin")&&password.equals("123"))){
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            return;
        }
        Boolean flag=checkBox2.isChecked();

        User user;
        if(flag){
            user=new User(username,password,flag);
        }else {
            user=new User();
        }
        user.saveUserBySharedPreferences(this);
        Intent intent =new Intent(MainActivity.this,ShowActivity.class);
        Bundle bundle=new Bundle();
        intent.putExtra("username",username);
        startActivity(intent);



    }

    @Override
    protected void onResume() {
        Log.i("tag","onResume");
        User user=new User();
        //SharedPreferences方式自动填写
        user.getUserBySharedPreferences(this);
        edit_username.setText( user.getName());
        edit_password.setText( user.getPwd());
        checkBox2.setChecked(user.getFlag());
        super.onResume();
    }
}
